import React, { PureComponent } from 'react';
import { Upload, Modal, message, } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getToken } from "@/utils/utils";
import { getMd5 } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common';

class PicturesWall extends PureComponent<any, any>  {
  constructor(props: any) {
    super(props);
    this.state = {
    file: {},
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };
  }
  componentWillMount() {
    const { data } = this.props;
    if (data) {
      this.setState({
        fileList: [{
          uid: -1,
          url: data,
        }],
      });
    }
  }
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file:any) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleSize=(file:any) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
      message.error('只能上传JPG或PNG图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能大于2MB!');
    }
    return isJPG && isLt2M;
  }
  handleChange = ({ fileList }:any) => {
    const { setPicture, onChange } = this.props;
    this.setState({ fileList });
    if (fileList[0] && fileList[0].response) {
      setPicture(fileList[0].response.data.fileUrl);
      onChange && onChange(fileList[0].response.data.fileUrl);
      return fileList[0].response.data.fileUrl;
    } else {
      setPicture(null);
      onChange && onChange(null);
    }
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const domain = window.g.url;
    const url = '/common/upload/img';
    const str = `${domain}${url}`;
    let md5 = getMd5('bizType=m18')
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
          <div style={{ marginTop: 8 }}>Upload</div>
        </button>
      );
    return (
      <div className="clearfix">
        <Upload
          action={str}
          headers= {{
            OptAuthorization: `${getToken()}`,
            ...getOptAuthHeaders(),
            shaSign: md5,
          }
          }
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          beforeUpload={this.handleSize}
        >
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="goods" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default PicturesWall;
